package org.outlook.eclipse.plugins.regexp4eclipse.component;

import org.eclipse.swt.custom.ST;
import org.eclipse.swt.widgets.Composite;
import org.outlook.eclipse.plugins.regexp4eclipse.actions.UndoManager;

public class StyledText extends org.eclipse.swt.custom.StyledText {

	public StyledText(Composite parent, int style) {
		super(parent, style);
	}

	@Override
	public void invokeAction(int action) {
		if (action == ActionCode.DELETE && getSelectionCount() > 0)
			action = ST.DELETE_NEXT;

		super.invokeAction(action);

		switch (action) {
		case ActionCode.UNDO:
			undo();
			break;
		case ActionCode.REDO:
			redo();
			break;
		case ActionCode.CLEAR:
			clear();
			break;
		}
	}

	private void undo() {
		if (undoManager != null)
			undoManager.undo();
	}

	private void redo() {
		if (undoManager != null)
			undoManager.redo();
	}

	private void clear() {
		super.setText("");
	}

	private UndoManager undoManager = null;

	/**
	 * @return Returns undoManager.
	 */
	public UndoManager getUndoManager() {
		return undoManager;
	}

	public void setUndoManager(UndoManager undoManager) {
		this.undoManager = undoManager;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.swt.widgets.Widget#dispose()
	 */
	public void dispose() {
		if (undoManager != null)
			undoManager.disconnect();

		super.dispose();
	}

	public static class ActionCode {
		public static final int UNDO = Integer.MAX_VALUE;

		public static final int REDO = UNDO - 1;

		public static final int CLEAR = UNDO - 2;

		public static final int DELETE = UNDO - 3;
	}
}
